package cn.zhangzhan.word.api.config;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Opt;
import cn.zhangzhan.common.core.domain.model.LoginUser;
import cn.zhangzhan.common.utils.SecurityUtils;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;


/**
 * 自动填充字段
 */
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        //time
        this.strictInsertFill(metaObject, "createTime", Date.class, DateUtil.date());
        this.strictUpdateFill(metaObject, "updateTime", Date.class, DateUtil.date());
        //by
        String username = SecurityUtils.getUsername();
        this.strictInsertFill(metaObject, "createBy", String.class, username);
        this.strictUpdateFill(metaObject, "updateBy", String.class, username);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.strictUpdateFill(metaObject, "updateTime", Date.class, DateUtil.date());
        Object o = SecurityUtils.getAuthentication().getPrincipal();
        Opt.ofNullable(o).ifPresent(o1 -> {
            if (o instanceof LoginUser) {
                String username = SecurityUtils.getUsername();
                Opt.ofBlankAble(username).ifPresent(u -> {
                    this.strictUpdateFill(metaObject, "updateBy", String.class, u);
                });
            }
        });
    }
}